#include <huniplacer_3d/InfoPanel.h>

#include <stdio.h>
#include <iostream>

#include <GL/gl.h>
#include <GL/freeglut.h>

InfoPanel::InfoPanel(unsigned int x, unsigned int y) :
				Picking("Info panel"), 
				x(x), y(y),
				width(width), height(height) {
}

void InfoPanel::add_part(PanelPart* new_part) {
	for (unsigned int i = 0; i < panel_parts.size(); i++) {
		if (new_part == panel_parts[i]) {
			return;
		}		
	}
	
	panel_parts.push_back(new_part);
	
	if (new_part->x < x) {
		x = new_part->x - 10;
	}

	if (new_part->width + new_part->x > this->width + this->x) {
		width = (new_part->x + new_part->width) - x + 15;
	}

	if (new_part->height + new_part->y > this->height + this->y) {
		height = (new_part->y + new_part->height) - this->y + 15;
	}
}

void InfoPanel::remove_part(PanelPart* old_part) {
	for (unsigned int i = 0; i < panel_parts.size(); i++) {
		if (old_part == panel_parts[i]) {
			panel_parts.erase(panel_parts.begin() + i);
			break;
		}	
	}
	
	width = 20;
	height = 20;
	
	//resize panel
	for (unsigned int i = 0; i < panel_parts.size(); i++) {
		if (panel_parts[i]->x < x) {
			x = panel_parts[i]->x - 10;
		}

		if (panel_parts[i]->width + panel_parts[i]->x > this->width + this->x) {
			width = (panel_parts[i]->x + panel_parts[i]->width) - x + 15;
		}

		if (panel_parts[i]->height + panel_parts[i]->y > this->height + this->y) {
			height = (panel_parts[i]->y + panel_parts[i]->height) - this->y + 15;
		}
	}
}

void InfoPanel::draw() {
	int screen_width, screen_height;
	screen_width = glutGet(GLUT_SCREEN_WIDTH); 
	screen_height = glutGet(GLUT_SCREEN_HEIGHT);

 	glMatrixMode (GL_PROJECTION);
	glPushMatrix();

	glLoadIdentity();

 	glOrtho (0, screen_width, screen_height, 0, 0, 1);

	glDisable(GL_DEPTH_TEST); 
 	glMatrixMode (GL_MODELVIEW);

	glPushMatrix();

	glLoadIdentity();
 	glTranslatef(0.375, 0.375, 0);

	//background color of the info panel
	set_color3f(0.1, 0.1, 0.1);
	glBegin(GL_LINES);
 		glVertex2f(x + 1, screen_height - height + 1); 
 		glVertex2f(x + width, screen_height - height + 1); 
 		glVertex2f(x + 1, screen_height - height + 1); 
 		glVertex2f(x + 1, screen_height - 1); 
 		glVertex2f(x + 1, screen_height - 1); 
 		glVertex2f(x + width, screen_height - 1); 
 		glVertex2f(x + width - 1, screen_height - height + 1); 
 		glVertex2f(x + width - 1, screen_height - 1); 
 	glEnd();

	set_color4f(0.05, 0.1, 0.1, 0.5);
	glDisable(GL_CULL_FACE);
	glBegin(GL_QUADS);
		glVertex2f(x, screen_height - height); 
		glVertex2f(x + width, screen_height - height); 
		glVertex2f(x + width, screen_height); 
		glVertex2f(x, screen_height);
	glEnd();
	//draw panel parts
	for (unsigned int i = 0; i < panel_parts.size(); i++) {
		glPushMatrix();
		panel_parts[i]->draw();
		glPopMatrix();
	}

	glEnable(GL_DEPTH_TEST);
	
 	glMatrixMode (GL_PROJECTION);
	glPopMatrix();

 	glMatrixMode (GL_MODELVIEW);
	glPopMatrix();
}
